<?php
	$enteredFName = $_POST['fNameField'];
	$enteredLName = $_POST['lNameField'];
	$enteredEmail = $_POST['emailField'];
	$enteredUName = $_POST['uNameField'];
	$enteredPassword = $_POST['passwordField'];
	
	$con = mysql_connect("localhost", "group5", "group5");//this will need to be changed for the group5 database
    if(!$con)
    {
		echo "Connection failed!";
        exit;
    }
	
	mysql_select_db("group5");//this will need to be changed for the group5 database
	
	$userQuery = "select * from USERS, USER_LOGIN where USERS.userId=USER_LOGIN.userId";
	$userResult = mysql_query($userQuery, $con);
	
	$safeFName = mysql_real_escape_String($enteredFName, $con);
	$safeLName = mysql_real_escape_String($enteredLName, $con);
	$safeEmail = mysql_real_escape_String($enteredEmail, $con);
	$safeUName = mysql_real_escape_String($enteredUName, $con);
	$safePassword = mysql_real_escape_String($enteredPassword, $con);

	$dupFlag = FALSE;
	while($row = mysql_fetch_row($userResult))
	{	
		$userId = $row[0];
		$firstName = $row[1];
		$lastName = $row[2];
		$email = $row[3];
		$userRoleId = $row[4];
		$userLoginId = $row[5];
		$userName = $row[6];
		$userPassword =$row[7];
		
		if($enteredUName == $userName)
		{
			$dupFlag = TRUE;
			break;
		}//end if
		elseif ($enteredEmail == $email)
		{
			$dupFlag = TRUE;
			break;
		}//end elseif
	}//end while
	
	if ($dupFlag == FALSE)
	{
		insertUser($safeFName,$safeLName,$safeEmail,$safeUName, $safePassword);
		$to = $safeEmail;
		$subject = 'CIRT Registration';
		$message = "Dear $safeFName,\r\rThank you for registering with CIRT's website. Your username and password are now active in our system and access is permited for sign-up of workshops.\r\rThank you, and have a wonderful day,\rGroup5";
		$headers = 'From: webmaster@fake.com'. '\r\n' . 'Reply-to: webmaster@fake.com' . '\r\n' . 'X-Mailer: PHP/' . phpversion();
		mail($to, $subject, $message);
		header("Location:registerPage.php?errorMsg=Registration successful! Please log in.");
	}
	else
	{
		header("Location:registerPage.php?errorMsg=The username or email has already been used.");
	}
	
	function getUserId($entEmail)
	{
		$userIdQuery = "select * from USERS where email='$entEmail'";
		$uIdResult = mysql_query($userIdQuery);
		while($row = mysql_fetch_row($uIdResult))
		{
			$userId = $row[0];
		}
		return $userId;
	}//end getUserId
	
	function insertUser($fname, $lname, $entEmail, $uname, $passwrd)
	{
		$insertUser = "insert into USERS (firstName,lastName,email,userRoleId) value ";
		$insertUser = $insertUser . "('$fname', '$lname', '$entEmail', 6)";//this needs to change when move from WAMP
		mysql_query($insertUser);
		
		$userId = getUserId($entEmail);

		$insertLogin = "insert into USER_LOGIN (userName,userPassword,userId) value ";
		$insertLogin = $insertLogin . "('$uname', '$passwrd', '$userId')";
		mysql_query($insertLogin);
	}//end insertUser
	
	mysql_close($con);
?>